package com.heima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.mapper.WmMaterialMapper;
import com.heima.mapper.WmNewsMapper;
import com.heima.mapper.WmNewsMaterialMapper;
import com.heima.mapper.WmUserMapper;
import com.heima.model.common.constants.NewsAutoScanConstants;
import com.heima.model.common.constants.WemediaConstants;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.service.WmNewsService;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UPENABLE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }

        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）TODO
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        }

        // ***发消息
        if(wmNews.getArticleId()!=null){
            Map<String,Object> mesMap = new HashMap<>();
            mesMap.put("enable",dto.getEnable());
            mesMap.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {
        boolean flag = updateById(wmNews);
        if (!flag) {
            ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间
        List<WmNews> ids = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime, new Date())
                .in(WmNews::getStatus, 4, 8)
                .select(WmNews::getId));
        List<Integer> idList = ids.stream()
                .map(x -> x.getId())
                .collect(Collectors.toList());
        return idList;
    }

    /**
     * 根据文章id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @param isSubmit  是否为提交 1 为提交 0为草稿
     * @return
     */
    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    @Transactional
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1 参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2保持会修改文章
        WmNews wmNews = new WmNews();
        //参数封装
        BeanUtils.copyProperties(dto, wmNews);
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        //处理文章封面
        String images = imageListToStr(dto.getImages(), webSite);
        if (StringUtils.isNotBlank(images)) {
            wmNews.setImages(images);
        }
        saveWmNews(wmNews);


        //3关联文章和素材的关系 （isSubmit = 1 提交时关联）
        //解析文章内容中的图片列表
        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contentList);
        //3.1关联文章 内容和素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() > 0) {
            saveRelativeInfoForContent(materials, wmNews.getId());
        }

        //3.2关联文章 封面和素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(dto, wmNews, materials);
        }

        // 4 发消息给admin审核文章
        Map map = new HashMap();
        map.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));


        //5返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /*
     * 保存文章封面和素材关系
     * */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //1.获取dto图片封面
        List<String> images = dto.getImages();

        //2.判断type是否为自动
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = materials.size();
            if (size > 0 && size <= 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null) {
                wmNews.setImages(imageListToStr(images, webSite));
            }
            updateById(wmNews);
        }

        //3.执行保存文章封面和素材关系
        if (images != null && images.size() > 0) {
            saveRelativeInfoForImage(images, wmNews.getId());
        }

    }

    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        images = images.stream().map(x -> x.replace(webSite, "").replace(" ", "")).collect(Collectors.toList());

        saveRelativeInfo(images, wmNewsId, WemediaConstants.WM_IMAGE_REFERENCE);

    }


    /*
     * 保存文章 内容和素材关系
     * */
    private void saveRelativeInfoForContent(List<String> materials, Integer wmNewsId) {
        saveRelativeInfo(materials, wmNewsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /*
     * 执行保存文章素材关系
     * */
    private void saveRelativeInfo(List<String> materials, Integer wmNewsId, Short type) {
        //1查询url查询素材对应的id

        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        //2 校验素材列表

        if (dbMaterials == null || dbMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
        }
        //2.判断文章素材是否存在
        Map<String, Integer> materialMap = dbMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        ArrayList<Integer> materialIds = new ArrayList<>();

        for (String url : materials) {
            Integer id = materialMap.get(url);
            //数据库素材被删除
            if (id == null) {
                CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }
            materialIds.add(id);
        }

        //3.执行保存
        wmNewsMaterialMapper.saveRelations(materialIds, wmNewsId, type);
    }


    /*
     * 抽取文章内容中的图片列表
     * */
    private List<String> parseContentImages(List<Map> contentList) {
        List<String> materials = new ArrayList<>();

        for (Map<String, String> content : contentList) {

            if (content.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imageUrl = content.get("value")
                        .replace(webSite, "")
                        .replace(" ", "");

                materials.add(imageUrl);
            }
        }

        return materials;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /*
     * 保存或修改文章
     * */
    private void saveWmNews(WmNews wmNews) {

        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE); // 上架


        if (wmNews.getId() == null) { //新增
            save(wmNews);
        } else { //修改
            //先删除文章和素材
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                            .eq(WmNewsMaterial::getNewsId, wmNews.getId())
            );
            updateById(wmNews);
        }

    }

    /*
     * 抽取前端文章封面列表转换成字符串
     * */
    private String imageListToStr(List<String> images, String webSite) {
        if (images.size() > 0) {
            return images.toString().replace("[", "")
                    .replace("]", "")
                    .replace(webSite, "")
                    .replace(" ", "");
        }

        return null;
    }

    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Autowired
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
            //设置当前页
        Integer currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //2.分页查询
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        //结果返回
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.条件封装查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //频道id
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //文章状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3.执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }
}
